package com.wenhui.schoolyardinfo.manager;

import android.content.Context;

import com.wenhui.schoolyardinfo.interceptor.AddCookiesInterceptor;
import com.wenhui.schoolyardinfo.interceptor.ReceivedCookiesInterceptor;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * author    : Urasaki
 * e-mail    : 1164688204@qq.com
 * date      : 2019/6/14 13:53
 * introduce : 联网okhttp3管理类
 */

public class Okhttp3Manager {

    public OkHttpClient client;
    private static Okhttp3Manager manager;
    private static final String TAG = "Okhttp3Manager";

    /**
     * 单例模式，所以构造函数私有化
     */
    private Okhttp3Manager(Context context) {
        //创建OkHttpClient对象
        client = new OkHttpClient.Builder()
                .connectTimeout(5000, TimeUnit.MILLISECONDS) //连接超时
                .readTimeout(5000, TimeUnit.MILLISECONDS) //读取超时
                .writeTimeout(5000, TimeUnit.MILLISECONDS) //写入超时
                .addInterceptor(new AddCookiesInterceptor(context)) //拦截器用于设置header
                .addInterceptor(new ReceivedCookiesInterceptor(context)) //拦截器用于接收并持久化cookie
//                .authenticator(new Authenticator() {
//                    @Nullable
//                    @Override
//                    public Request authenticate(Route route, Response response) throws IOException {
//                        LogManager.i(TAG, "authenticate*****");
//                        SharedPreferences sharedPreferences = context.getSharedPreferences("cookie", Context.MODE_PRIVATE);
//                        String cookie = sharedPreferences.getString("cookie", "");
//                        LogManager.i(TAG, "authenticator*****" + cookie);
//                        return response.request().newBuilder()
//                                .addHeader("Cookie", cookie)
//                                .build();
//                    }
//                })
//                //android客户端设置cookie自动保持
//                .cookieJar(new CookieJar() {
//                    //这里一定一定一定是HashMap<String, List<Cookie>>,是String,不是url.
//                    private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();
//
//                    @Override
//                    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
//                        cookieStore.put(url.host(), cookies);
//                        if (cookies != null) {
//                            LogManager.i(TAG, "Response cookies***" + cookies.toString());
//                        }
//                    }
//
//                    @Override
//                    public List<Cookie> loadForRequest(HttpUrl url) {
//                        List<Cookie> cookies = cookieStore.get(url.host());
//                        if (cookies != null) {
//                            LogManager.i(TAG, "Okhttp3Manager Request cookies*****" + cookies.toString());
//                            Cookie cookie = cookies.get(0);
//                            LogManager.i(TAG, "Okhttp3Manager Request cookie***" + cookie.toString());
//                        }
//                        return cookies != null ? cookies : new ArrayList<Cookie>();
//                    }
//                })
                .build();
    }

    /**
     * 线程安全的单例模式，整个项目中只有一个okhttp3实例
     *
     * @return
     */
    public static Okhttp3Manager getInstance(Context context) {
        if (manager == null) {
            synchronized (Okhttp3Manager.class) {
                if (manager == null) {
                    manager = new Okhttp3Manager(context);
                }
            }
        }
        return manager;
    }

    /**
     * post请求上传Form表单，异步方式，提交表单，是在子线程中执行的，需要切换到主线程才能更新UI
     *
     * @param url
     * @param bodyParams
     * @param callback
     */
    public void postAsyncFormOkhttp3(String url, Map<String, String> bodyParams, Callback callback) {
        // form 表单形式上传
        MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        //1.添加请求参数
        //遍历map中所有参数到builder
        if (bodyParams != null && bodyParams.size() > 0) {
            for (String key : bodyParams.keySet()) {
                if (bodyParams.get(key) != null) {//如果参数不是null，才把参数传给后台
                    multipartBodyBuilder.addFormDataPart(key, bodyParams.get(key));
                }
            }
        }

        //构建请求体
        RequestBody requestBody = multipartBodyBuilder.build();
        Request request = new Request.Builder().post(requestBody).url(url).build();
        //3 将Request封装为Call
        Call call = client.newCall(request);
        //4 执行Call
        call.enqueue(callback);
    }

    /**
     * post请求上传Form表单，异步方式，提交表单，是在子线程中执行的，需要切换到主线程才能更新UI
     *
     * @param url
     * @param header
     * @param bodyParams
     * @param callback
     */
    public void postAsyncFormOkhttp3(String url, String header, Map<String, String> bodyParams, Callback callback) {
        // form 表单形式上传
        MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        //1.添加请求参数
        //遍历map中所有参数到builder
        if (bodyParams != null && bodyParams.size() > 0) {
            for (String key : bodyParams.keySet()) {
                if (bodyParams.get(key) != null) {//如果参数不是null，才把参数传给后台
                    multipartBodyBuilder.addFormDataPart(key, bodyParams.get(key));
                }
            }
        }

        //构建请求体
        RequestBody requestBody = multipartBodyBuilder.build();
        Request request;
        if (header != null && !header.equals("")) {
            request = new Request.Builder()
                    .post(requestBody)
                    .addHeader("Cookie", header)
                    .url(url).build();
        } else {
            request = new Request.Builder()
                    .post(requestBody)
                    .url(url).build();
        }
        //3 将Request封装为Call
        Call call = client.newCall(request);
        //4 执行Call
        call.enqueue(callback);
    }

    /**
     * post的请求参数，构造RequestBody
     *
     * @param BodyParams
     * @return
     */
    private RequestBody setRequestBody(Map<String, String> BodyParams) {
        RequestBody body = null;
        okhttp3.FormBody.Builder formEncodingBuilder = new okhttp3.FormBody.Builder();
        if (BodyParams != null) {
            Iterator<String> iterator = BodyParams.keySet().iterator();
            String key = "";
            while (iterator.hasNext()) {
                key = iterator.next().toString();
                formEncodingBuilder.add(key, BodyParams.get(key));
                LogManager.i(TAG, "post_Params===" + key + "====" + BodyParams.get(key));
            }
        }
        body = formEncodingBuilder.build();
        return body;
    }

}
